package com.ddl.service.impl;

import com.ddl.common.enums.ResultType;
import com.ddl.common.exception.BusinessException;
import com.ddl.dao.PayFlowMapper;
import com.ddl.enums.PayType;
import com.ddl.pay.MchOrderInfoResult;
import com.ddl.pay.WeChatPayDto;
import com.ddl.pay.WeChatRequestPayDto;
import com.ddl.pay.WeixinPay;
import com.ddl.pojo.PayFlow;
import com.ddl.pojo.PayFlowWithBLOBs;
import com.ddl.service.IUserPayService;
import com.ddl.service.MoneyRecordService;
import com.ddl.util.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author dudianbo
 * @ClassName: ${CLASSNAME}
 * @Description: ${DESCRIPTION}
 * @date 2018/9/6
 */
@Service
public class UserPayServiceImpl implements IUserPayService {
    private static Logger logger = LoggerFactory.getLogger(UserPayServiceImpl.class);
    @Autowired
    PayFlowMapper payFlowMapper;
    @Autowired
    WeixinPay weixinPay;
    @Autowired
    MoneyRecordService moneyRecordService;


    /**
     * 微信支付
     * @param orderId
     */
    @Override
    public WeChatPayDto WeChatPay(String orderId, String ip, BigDecimal amount,String userId) {
        WeChatRequestPayDto weChatRequestPayDto=new WeChatRequestPayDto();
        weChatRequestPayDto.setTotal_fee((amount.movePointRight(2)).toString());
        weChatRequestPayDto.setOut_trade_no(orderId);
        weChatRequestPayDto.setTrade_type("MWEB");
        weChatRequestPayDto.setSpbill_create_ip(ip);
        weChatRequestPayDto.setBody("野蛮葡萄");
        logger.info("获取客户端ip={}",ip);
        WeChatPayDto weChatPayDto=weixinPay.payUnifiedorder(weChatRequestPayDto);
        PayFlow shoppingPayFlow=new PayFlow();
        shoppingPayFlow.setOrderId(orderId);
        List<PayFlowWithBLOBs> list=payFlowMapper.selectByRecord(shoppingPayFlow);
        if(list==null||list.size()==0){
            PayFlowWithBLOBs record=new PayFlowWithBLOBs();
            record.setOrderId(orderId);
            record.setAmount(amount);
            record.setDealStatus(ResultType.PROCESSING.getCode());
            record.setPayType(PayType.WECHAT_PAY.getValue());
            record.setUserId(userId);
            record.setBeforeSendRecord(JsonUtils.objToJson(weChatRequestPayDto));
            payFlowMapper.insertSelective(record);
        }
        return weChatPayDto;
    }

    @Override
    @Transactional
    public void paySuccess(PayFlowWithBLOBs shoppingPayFlow) {
        logger.info("支付成功入参shoppingPayFlow={}",shoppingPayFlow);
        PayFlow record=new PayFlow();
        record.setOrderId(shoppingPayFlow.getOrderId());
        List<PayFlowWithBLOBs> list=payFlowMapper.selectByRecord(record);
        if(list==null||list.size()==0){
            throw new BusinessException("无该笔订单");
        }
        record.setDealStatus(shoppingPayFlow.getDealStatus());
        payFlowMapper.updateByOrderId(record);
        PayFlowWithBLOBs payFlowWithBLOBs=list.get(0);
        BigDecimal gold=shoppingPayFlow.getAmount().movePointRight(2);
        moneyRecordService.proveder(Integer.parseInt(payFlowWithBLOBs.getUserId()), gold, "微信充值");
    }

    @Override
    public MchOrderInfoResult weixinQuery(String orderId) {
        MchOrderInfoResult mchOrderInfoResult=weixinPay.payOrderquery(orderId);
        if(StringUtils.isNotBlank(mchOrderInfoResult.getTrade_state_desc())){
            try {
                mchOrderInfoResult.setTrade_state_desc(new String(mchOrderInfoResult.getTrade_state_desc().getBytes("iso8859-1"), "utf-8"));
            }catch (Exception e) {
                logger.error("微信查询转错误信息有误{}",e);
            }
        }
        return mchOrderInfoResult;
    }
}
